package com.cyy.springbootinit.service.impl;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.constant.CommonConstant;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.mapper.BalanceAlarmMapper;
import com.cyy.springbootinit.model.dto.balanceAlarm.BalanceAlarmQueryRequest;
import com.cyy.springbootinit.model.entity.BalanceAlarm;
import com.cyy.springbootinit.model.entity.EquipmentInfo;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.BalanceAlarmVO;
import com.cyy.springbootinit.model.vo.UserVO;
import com.cyy.springbootinit.service.BalanceAlarmService;
import com.cyy.springbootinit.service.EquipmentInfoService;
import com.cyy.springbootinit.service.UserService;
import com.cyy.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 余额报警记录表服务实现
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@Service
@Slf4j
public class BalanceAlarmServiceImpl extends ServiceImpl<BalanceAlarmMapper, BalanceAlarm> implements BalanceAlarmService {

    @Resource
    private UserService userService;
    @Resource
    private EquipmentInfoService equipmentInfoService;

    /**
     * 校验数据
     *
     * @param balanceAlarm
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validBalanceAlarm(BalanceAlarm balanceAlarm, boolean add) {

        ThrowUtils.throwIf(balanceAlarm == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        Integer dormitoryId = balanceAlarm.getDormitoryId();
        Integer equipmentId = balanceAlarm.getEquipmentId();
        String note = balanceAlarm.getNote();
        Double deviceBalance = balanceAlarm.getDeviceBalance();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(note), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(deviceBalance == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(dormitoryId==null,ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(equipmentId==null,ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 获取查询条件
     *
     * @param balanceAlarmQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<BalanceAlarm> getQueryWrapper(BalanceAlarmQueryRequest balanceAlarmQueryRequest) {
        QueryWrapper<BalanceAlarm> queryWrapper = new QueryWrapper<>();
        if (balanceAlarmQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Integer id = balanceAlarmQueryRequest.getId();
        Integer dormitoryId = balanceAlarmQueryRequest.getDormitoryId();
        Integer equipmentId = balanceAlarmQueryRequest.getEquipmentId();
        String note = balanceAlarmQueryRequest.getNote();
        Integer isSolved = balanceAlarmQueryRequest.getIsSolved();
        Double deviceBalance = balanceAlarmQueryRequest.getDeviceBalance();
        Date alarmDate = balanceAlarmQueryRequest.getAlarmDate();
        Date createTime = balanceAlarmQueryRequest.getCreateTime();
        Date updateTime = balanceAlarmQueryRequest.getUpdateTime();
        String searchText = balanceAlarmQueryRequest.getSearchText();
        Date startDate = balanceAlarmQueryRequest.getStartDate();
        Date endDate = balanceAlarmQueryRequest.getEndDate();
        String sortField = balanceAlarmQueryRequest.getSortField();
        String sortOrder = balanceAlarmQueryRequest.getSortOrder();
        // todo 补充需要的查询条件
        // 获取当前日期
        LocalDate today = LocalDate.now();
// 如果 startDate 为空，设置为昨天（当前日期 - 1 天）
        if (ObjectUtils.isEmpty(startDate)) {
            LocalDate yesterday = today.minusDays(1); // 昨天
            startDate = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant()); // 转换为 Date 类型
        }

// 如果 endDate 为空，设置为明天（当前日期 + 1 天）
        if (ObjectUtils.isEmpty(endDate)) {
            LocalDate tomorrow = today.plusDays(1); // 明天
            endDate = Date.from(tomorrow.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant()); // 转换为 Date 类型
        }
        // 从多字段中搜索
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(note), "note", note);
        // JSON 数组查询
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(isSolved), "isSolved", isSolved);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(dormitoryId), "dormitoryId", dormitoryId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(equipmentId), "equipmentId", equipmentId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(deviceBalance), "deviceBalance", deviceBalance);
        queryWrapper.eq(ObjectUtils.isNotEmpty(createTime), "createTime", createTime);
        queryWrapper.eq((ObjectUtils.isNotEmpty(alarmDate)),"alarmDate",alarmDate);
        queryWrapper.gt(ObjectUtils.isNotEmpty(startDate),"alarmDate",startDate);
        queryWrapper.lt(ObjectUtils.isNotEmpty(endDate),"alarmDate",endDate);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取余额报警记录表封装
     *
     * @param balanceAlarm
     * @param request
     * @return
     */
    @Override
    public BalanceAlarmVO getBalanceAlarmVO(BalanceAlarm balanceAlarm, HttpServletRequest request) {
        if(balanceAlarm.getEquipmentId()==null) return  null;
        QueryWrapper<EquipmentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("equipmentId",balanceAlarm.getEquipmentId());
        EquipmentInfo equipmentInfo = equipmentInfoService.getOne(queryWrapper);
        System.out.println("获得equipment"+equipmentInfo);
        BalanceAlarmVO balanceAlarmVO = BalanceAlarmVO.objToVo(balanceAlarm);
        balanceAlarmVO.setEquipmentInfo(equipmentInfo);
        // 对象转封装类
        return balanceAlarmVO;
    }

    /**
     * 分页获取余额报警记录表封装
     *
     * @param balanceAlarmPage
     * @param request
     * @return
     */
    @Override
    public Page<BalanceAlarmVO> getBalanceAlarmVOPage(Page<BalanceAlarm> balanceAlarmPage, HttpServletRequest request) {
        List<BalanceAlarm> balanceAlarmList = balanceAlarmPage.getRecords();
        Page<BalanceAlarmVO> balanceAlarmVOPage = new Page<>(balanceAlarmPage.getCurrent(), balanceAlarmPage.getSize(), balanceAlarmPage.getTotal());
        if (CollUtil.isEmpty(balanceAlarmList)) {
            return balanceAlarmVOPage;
        }
        // 对象列表 => 封装对象列表
        List<BalanceAlarmVO> balanceAlarmVOList = balanceAlarmList.stream().map(balanceAlarm -> {
            return getBalanceAlarmVO(balanceAlarm,null);
        }).collect(Collectors.toList());

        balanceAlarmVOPage.setRecords(balanceAlarmVOList);
        return balanceAlarmVOPage;
    }

    @Override
    public Long getBalanceAlarmCountByDormitoryId(Integer dormitoryId) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
// 如果 startDate 为空，设置为昨天（当前日期 - 1 天）
        LocalDate yesterday = today.minusDays(1); // 昨天
        Date startDate = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant()); // 转换为 Date 类型
        return this.count(
                new QueryWrapper<BalanceAlarm>()
                        .eq("dormitoryId", dormitoryId)
                        .eq("isSolved", 0)
                        .gt("alarmDate",startDate));
    }
}
